package com.ycz.cglib;

import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.CallbackFilter;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.NoOp;

/**
 * @author ycz
 * @date 2021/7/3
 * 测试cglib
 */
public class TestCglib2 {

    /**
     * 生成动态代理类
     * @param args
     */
    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(ObjProxyClass1.class);

        // 3种回调方式
        CallbackFilter filter = new ObjProxyClassCallbackFilter();
        enhancer.setCallbackFilter(filter);
        // 1、MethodInterceptor：方法拦截器
        Callback interceprtor = new ObjProxyClassInterceptor();
        // 2、这个NoOp表示no operator，即什么操作也不做，代理类直接调用被代理的方法不进行拦截
        NoOp noOp = NoOp.INSTANCE;
        // 3、FixedValue：表示锁定方法返回值，无论被代理类的方法返回什么值，回调方法都返回固定值
        Callback fixedValue = new ObjProxyFixedValue();

        Callback[] callbacks=new Callback[]{interceprtor,noOp,fixedValue};
        enhancer.setCallbacks(callbacks);


        ObjProxyClass1 objProxyClass1 = (ObjProxyClass1) enhancer.create();
        objProxyClass1.print1();
        objProxyClass1.print2();
        int value = objProxyClass1.getPrintMethodFixedValue(10);
        System.out.println(value);
    }


}
